package com.lwd1513.designPattern.factory.strategy;

/**
 * @Author: 刘东（挂兰）
 * @Date: 2023/11/17 23:00:50
 * @Description:2个数字的各种运算
 */
public class Operation {

    public static void main(String[] args) {
        // 运算类
        Operation operation = new Operation(new Add());
        int result = operation.executeStrategy(3, 3);

        System.out.println("result = " + result);
        operation.setStrategy(new Subtraction());
        result = operation.executeStrategy(6, 8);

        System.out.println("result = " + result);

        /**
         * 优点 传入什么策略就用于什么行为 策略动态可以添加
         */
    }

    private CalculateStrategy strategy;

    public Operation(CalculateStrategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(CalculateStrategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.executeStrategy(num1, num2);
    }

}

/**
 * 计算策略
 */
interface CalculateStrategy {
    /**
     * 策略方法 接口隔离原则
     *
     * @param numA
     * @param numB
     * @return
     */
    Integer executeStrategy(Integer numA, Integer numB);
}

/**
 * 加策略
 */
class Add implements CalculateStrategy {

    @Override
    public Integer executeStrategy(Integer numA, Integer numB) {
        return numA + numB;
    }
}

/**
 * 减策略
 */
class Subtraction implements CalculateStrategy {

    @Override
    public Integer executeStrategy(Integer numA, Integer numB) {
        return numA - numB;
    }
}

